import request from '@/utils/request';

// 模拟数据API - 用于开发测试
const mockData = {
  // 模拟用户数据
  users: {
    'demo': {
      id: 1001,
      username: 'demo',
      name: '演示用户',
      phone: '13800000000',
      avatar: 'https://picsum.photos/100/100',
      email: 'demo@example.com',
      level: 'VIP会员',
      points: 1500,
      balance: 1200.50,
      register_time: '2024-01-15',
      is_distributor: true,
      distributor_level: '金牌'
    },
    '13800000000': {
      id: 1002,
      username: 'phone_user',
      name: '手机用户',
      phone: '13800000000',
      avatar: 'https://picsum.photos/100/100',
      email: '',
      level: '普通会员',
      points: 800,
      balance: 500,
      register_time: '2024-03-01',
      is_distributor: false
    },
    'wechat_user': {
      id: 1003,
      username: 'wechat_user',
      name: '微信用户',
      phone: '13800138001',
      avatar: 'https://picsum.photos/100/100',
      email: '',
      level: '白金会员',
      points: 2000,
      balance: 1800,
      register_time: '2024-02-10',
      is_distributor: true,
      distributor_level: '银牌'
    }
  },
  
  // 模拟设置数据
  settings: {
    notification: true,
    location: false,
    marketing: false
  }
};

// 模拟请求延迟
const mockDelay = (ms = 500) => new Promise(resolve => setTimeout(resolve, ms));

// 模拟响应格式
const mockResponse = (data, success = true, message = 'success') => ({
  code: success ? 200 : 400,
  message,
  data
});

// 开发模式标志
const isDevMode = true; // 设为true使用模拟数据，false使用真实API

export default {
  // 用户登录 - POST /user/login
  login: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        const { username, password } = data;
        
        if (username === 'demo' && password === '123456') {
          const user = mockData.users['demo'];
          return mockResponse({
            token: 'mock_token_' + Date.now(),
            userInfo: user
          });
        }
        
        return mockResponse(null, false, '用户名或密码错误');
      })();
    }
    return request.post('/user/login', data);
  },
  
  // 手机号登录 - POST /user/phone-login
  phoneLogin: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        const { phone, code } = data;
        console.log(data)
        if (phone === '13800000000' && code === '123456') {
          const user = mockData.users['13800000000'];
          return mockResponse({
            token: 'mock_token_' + Date.now(),
            userInfo: user
          });
        }
        
        return mockResponse(null, false, '手机号或验证码错误');
      })();
    }
    return request.post('/user/phone-login', data);
  },
  
  // 微信登录 - POST /user/wechat-login
  wechatLogin: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay(1000);
        const { code } = data;
        
        // 模拟微信授权流程
        console.log('模拟微信授权流程...');
        
        if (!code) {
          return mockResponse(null, false, '微信授权失败：未获取到code');
        }
        
        // 模拟微信服务器验证code
        console.log('向微信服务器验证code...');
        await mockDelay(800);
        
        // 模拟微信返回的openid和session_key
        const wechatResponse = {
          openid: 'mock_openid_' + Date.now(),
          session_key: 'mock_session_key_' + Date.now(),
          unionid: 'mock_unionid_' + Date.now()
        };
        
        console.log('微信授权成功，openid:', wechatResponse.openid);
        
        // 模拟根据openid查询用户信息
        await mockDelay(600);
        console.log('查询用户绑定信息...');
        
        // 检查是否已绑定用户
        let user = mockData.users['wechat_user'];
        let isNewUser = false;
        
        // 模拟新用户首次微信登录
        if (code === 'new_user') {
          isNewUser = true;
          user = {
            id: Date.now(),
            username: 'wx_' + Date.now(),
            name: '微信新用户',
            phone: '',
            avatar: '/static/images/wechat-default-avatar.png',
            email: '',
            level: '新用户',
            points: 50,
            balance: 0,
            register_time: new Date().toISOString().split('T')[0],
            is_distributor: false,
            wechat_info: {
              openid: wechatResponse.openid,
              unionid: wechatResponse.unionid
            }
          };
          console.log('检测到新用户，自动注册...');
        }
        
        // 模拟绑定微信信息到用户数据
        if (user) {
          user.wechat_info = {
            openid: wechatResponse.openid,
            unionid: wechatResponse.unionid,
            bind_time: new Date().toISOString()
          };
        }
        
        // 生成token
        const token = 'wx_token_' + Date.now();
        
        console.log('微信登录流程完成，返回用户数据');
        
        return mockResponse({
          token: token,
          userInfo: user,
          wechat_info: wechatResponse,
          is_new_user: isNewUser,
          message: isNewUser ? '欢迎新用户！已自动为您创建账号' : '微信登录成功'
        });
      })();
    }
    return request.post('/user/wechat-login', data);
  },
  
  // 用户注册 - POST /user/register
  register: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        const { username, password, phone, code } = data;
        
        if (username && password && phone && code === '123456') {
          // 模拟新用户注册成功
          const newUser = {
            id: Date.now(),
            username,
            name: username,
            phone,
            avatar: '/static/images/default-avatar.png',
            email: '',
            level: '新用户',
            points: 100,
            balance: 0,
            register_time: new Date().toISOString().split('T')[0],
            is_distributor: false
          };
          
          return mockResponse({
            token: 'mock_token_' + Date.now(),
            userInfo: newUser
          });
        }
        
        return mockResponse(null, false, '注册信息不完整或验证码错误');
      })();
    }
    return request.post('/user/register', data);
  },
  
  // 发送验证码 - POST /user/send-sms-code
  sendSmsCode: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay(1000);
        const { phone, type } = data;
        
        if (phone && phone.length === 11) {
          return mockResponse({
            code: '123456',
            expire_time: 300
          });
        }
        
        return mockResponse(null, false, '手机号格式错误');
      })();
    }
    return request.post('/user/send-sms-code', data);
  },
  
  // 获取用户信息 - GET /user/info
  getUserInfo: () => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        // 模拟从token中获取用户信息
        const user = mockData.users['demo'];
        return mockResponse(user);
      })();
    }
    return request.get('/user/info');
  },
  
  // 更新用户信息 - PUT /user/info
  updateUserInfo: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        const user = mockData.users['demo'];
        const updatedUser = { ...user, ...data };
        
        return mockResponse(updatedUser);
      })();
    }
    return request.put('/user/info', data);
  },
  
  // 修改密码 - POST /user/change-password
  changePassword: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        const { oldPassword, newPassword } = data;
        
        if (oldPassword === '123456' && newPassword) {
          return mockResponse({ message: '密码修改成功' });
        }
        
        return mockResponse(null, false, '原密码错误');
      })();
    }
    return request.post('/user/change-password', data);
  },
  
  // 绑定手机号 - POST /user/bind-phone
  bindPhone: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        const { phone, code } = data;
        
        if (phone && code === '123456') {
          return mockResponse({ message: '手机号绑定成功' });
        }
        
        return mockResponse(null, false, '验证码错误');
      })();
    }
    return request.post('/user/bind-phone', data);
  },
  // 上传头像 - POST /user/upload-avatar
  uploadAvatar: (data) => {
    return request.post('/index/uploadFile', data);
  },
  
  // 获取用户设置 - GET /user/settings
  getUserSettings: () => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        return mockResponse(mockData.settings);
      })();
    }
    return request.get('/user/settings');
  },
  
  // 更新用户设置 - PUT /user/settings
  updateUserSettings: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        const updatedSettings = { ...mockData.settings, ...data };
        
        return mockResponse(updatedSettings);
      })();
    }
    return request.put('/user/settings', data);
  },
  
  // 实名认证 - POST /user/real-name-auth
  realNameAuth: (data) => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        const { real_name, id_card } = data;
        
        if (real_name && id_card) {
          return mockResponse({
            status: 'success',
            message: '实名认证成功'
          });
        }
        
        return mockResponse(null, false, '实名认证信息不完整');
      })();
    }
    return request.post('/user/real-name-auth', data);
  },
  
  // 获取实名认证状态 - GET /user/auth-status
  getAuthStatus: () => {
    if (isDevMode) {
      return (async () => {
        await mockDelay();
        return mockResponse({
          status: 'unverified',
          message: '未实名认证'
        });
      })();
    }
    return request.get('/user/auth-status');
  }
};